<?php
global $data, $pc_res, $mobile_res, $all_resolutions, $current_canvas, $current_area, $success, $error;

// 处理登录
if (isset($_POST['action']) && $_POST['action'] === 'login') {
    $password = trim($_POST['password']);
    if ($password === ADMIN_PASSWORD) {
        $_SESSION['logged_in'] = true;
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $error = '密码错误，请重试';
    }
}

// 处理退出
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// 验证登录状态
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
    include 'templates/login.php';
    exit;
}

// 已登录，处理各种操作
$data = read_data();
$pc_res = json_decode(PC_RESOLUTIONS, true);
$mobile_res = json_decode(MOBILE_RESOLUTIONS, true);
$all_resolutions = array_merge($pc_res, $mobile_res);
$current_canvas = null;
$current_area = null;
$success = '';

// 处理创建项目
if (isset($_POST['action']) && $_POST['action'] === 'create_project') {
    $name = trim($_POST['canvas_name']);
    if (!empty($name)) {
        $project_id = generate_id();
        $data[$project_id] = [
            'name' => $name,
            'canvas_list' => []
        ];
        save_data($data);
        $success = '项目创建成功';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?action=edit_project&id=' . $project_id);
        exit;
    } else {
        $error = '项目名称不能为空';
    }
}
// 处理重命名项目
if (isset($_POST['action']) && $_POST['action'] === 'rename_project' && $_POST['project_id']) {
    $project_id = $_POST['project_id'];
    $new_name = trim($_POST['new_name']);
    if (!empty($new_name)) {
        $data[$project_id]['name'] = $new_name;
        save_data($data);
        $success = '重命名成功';
    } else {
        $error = '重命名失败，请检查ID和名称';
    }
}

// 处理创建画板
if (isset($_POST['action']) && $_POST['action'] === 'create_canvas' && $_POST['project_id']) {
    $name = trim($_POST['canvas_name']);
    $project_id = $_POST['project_id'];
    if (!empty($name) && !empty($project_id)) {
        $canvas_id = generate_id();
        $data[$project_id]['canvas_list'][$canvas_id] = [
            'name' => $name,
            'areas' => [],
            'canvas_view' => [ // 保存画布视图状态（缩放、偏移）
                'scale' => 100,
                'offsetX' => 0,
                'offsetY' => 0,
                'sidebar' => 1,
            ]
        ];
        save_data($data);
        $success = '画板创建成功';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?action=edit_canvas&id=' . $canvas_id);
        exit;
    } else {
        $error = '画板名称不能为空';
    }
}

// 处理重命名画板
if (isset($_POST['action']) && $_POST['action'] === 'rename_canvas' && $_POST['project_id']) {
    $canvas_id = $_POST['canvas_id'];
    $project_id = $_POST['project_id'];
    $new_name = trim($_POST['new_name']);
    if (!empty($new_name) && isset($data[$project_id]['canvas_list'][$canvas_id])) {
        $data[$project_id]['canvas_list'][$canvas_id]['name'] = $new_name;
        save_data($data);
        $success = '画板重命名成功';
    } else {
        $error = '重命名失败，请检查画板ID和名称';
    }
}

// 处理保存画布视图状态（缩放、偏移）
if (isset($_POST['action']) && $_POST['action'] === 'save_canvas_view') {
    $project_id = $_POST['project_id'];
    $canvas_id = $_POST['canvas_id'];
    $scale = (int)$_POST['scale'];
    $offsetX = (int)$_POST['offsetX'];
    $offsetY = (int)$_POST['offsetY'];
    $sidebar = (int)$_POST['sidebar'];
    if (isset($data[$project_id]['canvas_list'][$canvas_id])) {
        $data[$project_id]['canvas_list'][$canvas_id]['canvas_view'] = [
            'scale' => $scale,
            'offsetX' => $offsetX,
            'offsetY' => $offsetY,
            'sidebar' => $sidebar,
        ];
        save_data($data);
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => '画板不存在']);
    }
    exit;
}

// 处理删除画板（同时删除关联的HTML文件）
if (isset($_GET['action']) && $_GET['action'] === 'delete_canvas' && isset($_GET['id']) && isset($_GET['project_id']) ) {
    $canvas_id = $_GET['id'];
    $project_id = $_GET['project_id'];
    if (isset($data[$project_id]['canvas_list'][$canvas_id])) {
        // 删除该画板下所有区域的HTML文件
        foreach ($data[$project_id]['canvas_list'][$canvas_id]['areas'] as $area) {
            if (!empty($area['html_file'])) {
                delete_area_html($area['html_file']);
            }
        }
        unset($data[$project_id]['canvas_list'][$canvas_id]);
        save_data($data);
        $success = '画板删除成功';
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $error = '删除失败，画板不存在';
    }
}

// 处理添加区域（创建对应的HTML文件，初始化位置在画布中心）
if (isset($_POST['action']) && $_POST['action'] === 'add_area') {
    $project_id = $_POST['project_id'];
    $canvas_id = $_POST['canvas_id'];
    $resolution = $_POST['resolution'];
    $area_name = trim($_POST['area_name']); // 区域名称
    $html_content = trim($_POST['html_content']); // 新增：HTML内容

    if (empty($area_name)) {
        $error = '区域名称不能为空';
    } elseif (empty($html_content)) {
        $error = 'HTML内容不能为空';
    } else {
        list($w, $h) = explode('x', $resolution);
        if (isset($data[$project_id]['canvas_list'][$canvas_id]) && is_numeric($w) && is_numeric($h)) {
            $area_id = generate_id();
            $html_file = $area_id . '.html'; // HTML文件名用区域ID命名

            // 保存HTML内容到文件
            if (!save_area_html($html_file, $html_content)) {
                $error = '保存HTML文件失败，请检查目录权限';
                header('Location: ' . $_SERVER['PHP_SELF'] . '?action=edit_canvas&id=' . $canvas_id);
                exit;
            }

            // 初始化位置：画布中心
            $canvas_center_x = 1000; // 画布中心X坐标（基于无限画布设计）
            $canvas_center_y = 600;  // 画布中心Y坐标
            $init_x = $canvas_center_x - ($w / 2);
            $init_y = $canvas_center_y - ($h / 2);

            // 添加区域数据到JSON（包含x、y位置）
            $data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id] = [
                'name' => $area_name,
                'width' => (int)$w,
                'height' => (int)$h,
                'html_file' => $html_file,
                'x' => (int)$init_x, // 水平位置（像素）
                'y' => (int)$init_y  // 垂直位置（像素）
            ];
            save_data($data);
            $success = '区域添加成功';
            header('Location: ' . $_SERVER['PHP_SELF'] . '?action=edit_canvas&id=' . $canvas_id);
            exit;
        } else {
            $error = '添加区域失败，请检查参数';
        }
    }
}

// 处理编辑区域（AJAX）
if (isset($_POST['action']) && $_POST['action'] === 'edit_area_ajax') {
    $project_id = $_POST['project_id'];
    $canvas_id = $_POST['canvas_id'];
    $area_id = $_POST['area_id'];
    $area_name = trim($_POST['area_name']);
    $html_content = trim($_POST['html_content']);
    $resolution = $_POST['resolution'];
    list($w, $h) = explode('x', $resolution);

    $response = ['status' => 'error', 'message' => '操作失败'];
    if (empty($area_name)) {
        $response['message'] = '区域名称不能为空';
    } elseif (empty($html_content)) {
        $response['message'] = 'HTML内容不能为空';
    } elseif (isset($data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id])) {
        $area = &$data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id];

        $area['width'] = (int)$w;
        $area['height'] = (int)$h;
        // 更新区域名称
        $area['name'] = $area_name;
        // 更新HTML文件内容
        if (save_area_html($area['html_file'], $html_content)) {
            save_data($data);
            $response = ['status' => 'success', 'message' => '区域更新成功', 'name' => $area_name];
        } else {
            $response['message'] = '更新HTML文件失败，请检查目录权限';
        }
    } else {
        $response['message'] = '区域不存在';
    }
    echo json_encode($response);
    exit;
}

// 处理保存区域位置（AJAX请求）
if (isset($_POST['action']) && $_POST['action'] === 'save_area_position') {
    $project_id = $_POST['project_id'];
    $canvas_id = $_POST['canvas_id'];
    $area_id = $_POST['area_id'];
    $x = (int)$_POST['x'];
    $y = (int)$_POST['y'];

    if (isset($data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id])) {
        $data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id]['x'] = $x;
        $data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id]['y'] = $y;
        save_data($data);
        echo json_encode(['status' => 'success', 'message' => '位置保存成功']);
    } else {
        
        echo json_encode(['status' => 'error', 'message' => '区域不存在']);
    }
    exit;
}

// 处理删除区域（同时删除对应的HTML文件）
if (isset($_POST['action']) && $_POST['action'] === 'delete_area_ajax') {
    $project_id = $_POST['project_id'];
    $canvas_id = $_POST['canvas_id'];
    $area_id = $_POST['area_id'];
    $response = ['status' => 'error', 'message' => '删除失败'];

    if (isset($data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id])) {
        // 删除HTML文件
        $html_file = $data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id]['html_file'];
        delete_area_html($html_file);
        // 删除区域数据
        unset($data[$project_id]['canvas_list'][$canvas_id]['areas'][$area_id]);
        save_data($data);
        $response = ['status' => 'success', 'message' => '区域删除成功'];
    }
    echo json_encode($response);
    exit;
}

// 显示画板编辑页
if (isset($_GET['action']) && $_GET['action'] === 'edit_canvas'  && isset($_GET['project_id']) ) {
    $project_id = $_GET['project_id'];
    $current_canvas_list = $data[$project_id]['canvas_list'];
    if(isset($_GET['canvas_id'])){
            $canvas_id = $_GET['canvas_id'];
                if($canvas_id){
        $current_canvas = $data[$project_id]['canvas_list'][$canvas_id];
    }
    }



    
    include 'templates/canvas.php';
    exit;
   
}